package com.jarchie.androiddev.ext

import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.target.DrawableImageViewTarget
import com.bumptech.glide.request.transition.Transition
import com.jarchie.androiddev.utils.DisplayUtil
import jp.wasabeef.glide.transformations.BlurTransformation
import jp.wasabeef.glide.transformations.RoundedCornersTransformation

fun View.setVisibility(condition: Boolean) {
    this.visibility = if (condition) View.VISIBLE else View.GONE
}

fun ImageView.setImageUrl(url: String?, isCircle: Boolean = false, radius: Int = 0) {
    if (TextUtils.isEmpty(url)){
        visibility = View.GONE
        return
    }
    visibility = View.VISIBLE
    val builder = Glide.with(this).load(url)
    if (isCircle){
        builder.transform(CircleCrop())
    }else if (radius>0){
        builder.transform(RoundedCornersTransformation(DisplayUtil.dp2px(radius),0))
    }
    val layoutParams = this.layoutParams
    if (layoutParams!=null && layoutParams.width>0 && layoutParams.height>0){
        builder.override(layoutParams.width,layoutParams.height)
    }
    builder.into(this)
}

fun ImageView.setBlurImageUrl(blur: String, radius: Int) {
    Glide.with(this).load(blur).override(radius)
        .transform(BlurTransformation()).dontAnimate().into(object : DrawableImageViewTarget(this) {
            override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                super.onResourceReady(resource, transition)
                background = resource
            }
        })
}